﻿class User < ActiveRecord::Base
  
  acts_as_paranoid
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :recoverable, :registerable, :rememberable, :trackable, :authentication_keys => [:login]

  belongs_to :department
  has_many :group_users
  has_many :groups, through: :group_users  

  validates_confirmation_of :password

  def role_enum role_value
       {
      "0" => "没任何权限",
      "1" => "信息员",
      "2" => "新媒体组",
      "3" => "校报租",
      "4" => "媒体华理组",
      "5" => "记者组",
      "6" => "浏览组",
      "7" => "归档组",
      "8" => "超级管理员" 
    }[role_value.to_s]
  end

  def permissions
    permission_ids = GroupPermission.where(:group_id => groups.pluck(:id)).select("distinct permission_id").pluck(:permission_id)
    Permission.where(:id => permission_ids)
  end

  def admin?
    groups.exists?(:name => "管理员")
  end

  def info_man?
    groups.exists?(:name => "信息员")
  end

  def xinmeiti?
    groups.exists?(:name => "新媒体组")
  end

  def meitihuali?
    groups.exists?(:name => "媒体华理组")
  end
  
  def xiaobao?
    groups.exists?(:name => "校报组")
  end
  
  def waixuan?
    groups.exists?(:name => "外宣组")
  end
  def dangan?
    groups.exists?(:name => "归档组")
  end

  def self.find_for_database_authentication(warden_conditions)    
    conditions = warden_conditions.dup
    if login = conditions.delete(:email)
      where(conditions).where(["lower(login) = :value OR lower(email) = :value", { :value => login.downcase }]).first
    else
      where(conditions).first
    end
  end

  class << self

  end

end
